package com.jmp.api.service.impl;

import com.github.vioao.wechat.api.TicketApi;
import com.github.vioao.wechat.api.TokenApi;
import com.github.vioao.wechat.bean.response.ticket.TicketResponse;
import com.github.vioao.wechat.bean.response.token.TokenResponse;
import com.jmp.api.service.WechatBaseService;
import lombok.extern.slf4j.Slf4j;
import one.stand.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WechatBaseServiceImpl implements WechatBaseService {
    private static final Long CACHE_TIMEOUT = 60 * 5L;//5分钟

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String getWxToken(String appId, String appSecret) {
        String key = "wx:token:" + appId;
        return redisUtil.get(key, () -> {
            TokenResponse tokenResponse = TokenApi.token(appId, appSecret);
            log.info("获取微信token:{}", tokenResponse);
            return tokenResponse.getAccessToken();
        }, CACHE_TIMEOUT);
    }

    @Override
    public String getTicket(String appId, String appSecret) {
        String key = "wx:ticket:" + appId;
        return redisUtil.get(key, () -> {
            String token = getWxToken(appId, appSecret);
            TicketResponse ticketResponse = TicketApi.getTicket(token);
            log.info("获取微信token:{}", ticketResponse);
            return ticketResponse.getTicket();
        }, CACHE_TIMEOUT);
    }

}
